package com.boss.sever;

import com.boss.common.EncryptionUtils;
import com.boss.common.FileUtils;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.*;
import java.util.concurrent.*;

/**
 * @author 郑炆杰
 */
public class Server extends Observable {
    private static final int PORT = 12345;
    private final Map<String, ClientHandler> onlineClients = new ConcurrentHashMap<>();
    private final Map<String, List<String>> offlineMessages = new ConcurrentHashMap<>();
    private final List<Observer> observers = new CopyOnWriteArrayList<>();

    public static void main(String[] args) {
        Server server = new Server();
        server.start();
    }

    public void start() {
        Thread thread = startListen();
        startCommandLine();
        thread.interrupt();
        System.exit(0);
    }

    public void startCommandLine() {
        Scanner scanner = new Scanner(System.in);
        while (true) {
            String input = scanner.nextLine();
            if ("exit".equals(input)) {
                break;
            } else if (input.startsWith("show ")) {
                try {
                    String[] parts = input.split(" ");
                    String filePath = parts[1];
                    String content = FileUtils.readFile(filePath);
                    System.out.println(content);
                } catch (IOException e) {
                    System.out.println("Error reading file: " + e.getMessage());
                }
            }
        }
    }

    public Thread startListen() {
        Thread thread = new Thread(() -> {
            try (ServerSocket serverSocket = new ServerSocket(PORT)) {
                System.out.println("服务器已启动，等待连接...");
                while (!Thread.currentThread().isInterrupted()) {
                    Socket socket = serverSocket.accept();
                    ClientHandler clientHandler = new ClientHandler(socket, this);
                    new Thread(clientHandler).start();
                }
            } catch (IOException e) {
                System.out.println("服务器启动失败");
            }
        });
        thread.start();
        return thread;
    }

    @Override
    public synchronized void addObserver(Observer o) {
        observers.add(o);
    }

    public synchronized void removeObserver(Observer o) {
        observers.remove(o);
    }

    public void notifyObservers(String message) {
        for (Observer observer : observers) {
            observer.update(this, message);
        }
    }

    public synchronized void addClient(String clientId, ClientHandler clientHandler) {
        onlineClients.put(clientId, clientHandler);
        if (offlineMessages.containsKey(clientId)) {
            for (String message : offlineMessages.get(clientId)) {
                clientHandler.sendMessage(message);
            }
            offlineMessages.remove(clientId);
        }
    }

    public synchronized void removeClient(String clientId) {
        onlineClients.remove(clientId);
    }

    public void sendMessageToClient(String clientId, String message) {
        ClientHandler client = onlineClients.get(clientId);
        if (client != null) {
            client.sendMessage(message);
        } else {
            offlineMessages.computeIfAbsent(clientId, k -> new ArrayList<>()).add(message);
        }
    }

    public void sendMessageToAll(String message) {
        notifyObservers(message);
    }

    public String decrypt(String encryptedText) throws Exception {
        return EncryptionUtils.decrypt(encryptedText);
    }

    public ClientHandler getClientHandler(String clientId) {
        return onlineClients.get(clientId);
    }

    public static class ClientHandler implements Runnable, Observer {
        private final Socket socket;
        private final Server server;
        private BufferedReader in;
        private PrintWriter out;
        private String clientId;

        public ClientHandler(Socket socket, Server server) {
            this.socket = socket;
            this.server = server;
        }

        public void sendMessage(String message) {
            out.println(message);
        }

        public String readMessage() throws IOException {
            return in.readLine();
        }

        @Override
        public void run() {
            try {
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                out = new PrintWriter(socket.getOutputStream(), true);

                // 生成唯一的客户端ID
                clientId = UUID.randomUUID().toString();
                server.addClient(clientId, this);
                server.addObserver(this);
                out.println("你的ID是: " + clientId);
                System.out.println("客户端连接成功: " + clientId);

                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    com.boss.sever.AbstractMessageHandler handler = com.boss.sever.MessageHandlerFactory.createHandler(server, clientId, inputLine);
                    handler.handle();
                }
            } catch (IOException e) {
                System.out.println("客户端断开连接: " + clientId);
            } finally {
                server.removeClient(clientId);
                server.removeObserver(this);
                try {
                    socket.close();
                } catch (IOException e) {
                    System.out.println("关闭客户端连接失败: " + clientId);
                }
            }
        }

        @Override
        public void update(Observable o, Object message) {
            sendMessage((String) message);
        }
    }
}
